package com.wave.wavesystem.ai.tool;

import cn.hutool.core.util.StrUtil;
import com.wave.wavesystem.ai.enums.MessageRole;
import com.wave.wavesystem.ai.rag.WaveMarkDownReader;
import com.wave.wavesystem.serve.pojo.entity.Comment;
import com.wave.wavesystem.serve.service.ICommentService;
import com.wave.wavesystem.serve.service.IPostService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.document.Document;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class PostTools {

    @Resource
    private IPostService postService;

    @Resource
    private ICommentService commentService;

    @Resource
    private WaveMarkDownReader markDownReader;

    @Resource
    private VectorStore waveVectorStore;

    public PostTools() {
        log.info("PostTools 被加载....");
    }

    @Tool(description = "查询帖子总数")
    public String postCounts() {
        return String.valueOf(postService.count());
    }

    @Tool(description = "帖子审批通过功能", returnDirect = true)
    public String postApproval(
            @ToolParam(description = "违规内容", required = false) String rejectReason,
            ToolContext toolContext) {
        Long postId = (Long) toolContext.getContext().get("postId");
        String postContent = (String) toolContext.getContext().get("postContent");
        if (StrUtil.isBlank(rejectReason)) {
            boolean approval = postService.approvalById(postId, MessageRole.ASSISTANT.getRole());
            if (approval) {
                // 更新知识库
                List<Document> documents = markDownReader.readByMarkDownContent(postContent);
                waveVectorStore.add(documents);
            }
            return "审批通过,请调用autoComment 对文章进行100字左右的评论。要求积极合理";
        } else {
            boolean rejected = postService.rejectPost(postId, rejectReason);
            return "审批失败";

        }
    }

    @Tool(description = "对文章评论功能")
    public String autoComment(
            @ToolParam(description = "评论内容") String comment,
            ToolContext toolContext) {
        Comment temp = new Comment();
        Long postId = (Long) toolContext.getContext().get("postId");
        temp.setPostId(postId);
        temp.setContent(comment);
        temp.setAuthorId(778899L);
        temp.setStatus(1);
        boolean success = commentService.save(temp);
        if (success) {
            return "评论成功";
        } else {
            return "评论结束";
        }
    }

}
